package com.pb.wkflow.core.utils;

import com.pb.wkflow.api.exception.ApprovalException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

/**
 * @author 苗益辉
 * @date 2022/5/17 14:22
 */
public class RestTemplateUtil {

    private static final RestTemplate restTemplate = new RestTemplate();

    public static String post(String url, String paramJson) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
        httpHeaders.set("token","");
        HttpEntity http = new HttpEntity(paramJson, httpHeaders);
        String result = null;
        try{
            result = restTemplate.postForObject(url, http, String.class);
        }catch (Exception e) {
            if(e instanceof HttpServerErrorException) {
                throw new ApprovalException(((HttpServerErrorException) e).getResponseBodyAsString());
            }else {
                throw new ApprovalException(e.getMessage());
            }
        }
        return result;
    }
}
